<template>
  <span @click="computeDistance">测量距离</span>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted,toRefs } from "vue";
const { proxy } = getCurrentInstance();
import { usePopupStore } from "@/stores/popupStore";

const {showPopup}=usePopupStore()
import { drawGraph } from "@/zondyTools/ol-api/olDraw";
/* 构建放画笔的数据源 */
const source = new ol.source.Vector();
const layer = new ol.layer.Vector({
  source: source,
  id: "draw-line-layer",
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: "blue",
      width: 4,
    }),
  }
  )
});
let drawLine = null;
let $map = null;


/* 挂载时，将图层先添加到地图上，再实例化画笔 */
onMounted(() => {
  $map = proxy.$map;
  $map.addLayer(layer);
});

/* 点击事件，触发画笔绘制 */
function computeDistance() {
  drawLine = drawGraph({ type: "LineString", source });
  $map.addInteraction(drawLine);

  drawLine.on("drawend", function (e) {
    
    /* 获取绘制的线段坐标数据 */
    const feature = e.feature;
    const geometry = feature.getGeometry();
    const coordinates = geometry.getCoordinates();
    //console.log(coordinates)
    /* 利用turf库计算距离 */
    var line = turf.lineString(coordinates);
    const distance = turf.length(line, { units: "miles" });

    /* 计算线段中心，将长度以弹窗形式展示 */
    const center = turf.center(line);

    showPopup({content:{ '长度': distance.toFixed(4) + " 公里" },position:center.geometry.coordinates})

    /* 关闭画笔 */
    $map.removeInteraction(drawLine);
    
    
  });
}

</script>

<style scoped></style>
